/*
 * @Author: wwssaabb
 * @Date: 2021-11-23 10:19:17
 * @LastEditTime: 2021-11-23 10:42:41
 * @FilePath: \handwritten-code\demo\浅拷贝.js
 */

//实现浅拷贝

//方法1，扩展符...
/*
function shallowCopy(target) {
  if (typeof target !== 'object' || target === null) {
    return target
  }

  return Array.isArray(target) ? [...target] : {
    ...target
  }
}
*/
//方法2， Object.assign


// for in 遍历
function shallowCopy(target) {
  if (typeof target !== 'object' || target === null) return target
  let res = Array.isArray(target) ? [] : {}
  for (const key in target) {
    if (Object.hasOwnProperty.call(target, key)) {
      res[key] = target[key]
    }
  }
  return res
}


/*
function shallowCopy(target){
  if(typeof target !=='object'||target===null){
    return target
  }

}*/


let a = [1, 2, 23, 3, {
  a: 1,
  b: 2,
  c: {
    d: 3
  }
}, {
  f: 6
}]
let res = shallowCopy(a)
// let res = Object.assign(a)
console.log(res)
res[4].a = 2
console.log(res)
console.log(a)